// src/store/modules/task.js
import { createTask, fetchTasks, updateTaskStatus, updateTask, deleteTask } from '@/api/task';

const state = {
  tasks: [], // 如果有需要保存的任务列表状态，可以在这里定义
  statusForm: {
    id: null,
    name: '',
    status: ''
  }
};

const mutations = {
  SET_TASKS(state, tasks) {
    state.tasks = tasks;
  },
  UPDATE_STATUS_FORM(state, formData) {
    state.statusForm = { ...state.statusForm, ...formData };
  },
};

const actions = {
  async addTask({ commit }, taskForm) {
    try {
      const result = await createTask(taskForm);
      console.log('任务创建成功:', result);
      // 如果需要更新本地状态，可以在这里调用 mutations
      // commit('SET_TASKS', [...state.tasks, result]);
    } catch (error) {
      console.error('任务创建失败:', error);
      throw error;
    }
  },
  async fetchTasks({ commit }, query = {}) {
    try {
      const response = await fetchTasks(query);
      commit('SET_TASKS', response.data);
    } catch (error) {
      console.error('获取任务列表失败:', error);
      throw error;
    }
  },
  async updateTaskStatus({ commit }, { id, status }) {
    console.log('更新任务状态 - ID:', id, '状态:', status); // 打印传入的参数

    try {
      await updateTaskStatus(id, status);
      this._vm.$message({
        message: '状态更新成功，工具已归库',
        type: 'success'
      });
    } catch (error) {
      console.error('更新状态失败:', error);
      this._vm.$message({
        message: '状态更新失败，请稍后再试',
        type: 'error'
      });
    }
  },
  async updateTask({ commit }, { id, taskData }) {
    try {
      const result = await updateTask(id, taskData);
      console.log('任务更新成功');
      commit('SET_TASKS', state.tasks.map(task => task.id === id ? { ...task, ...taskData } : task)); // 更新本地状态
    } catch (error) {
      console.error('任务更新失败:', error);
      throw error;
    }
  },
  async deleteTask({ commit }, id) {
    try {
      await deleteTask(id);
      console.log('任务删除成功');
      commit('SET_TASKS', state.tasks.filter(task => task.id !== id)); // 更新本地状态
    } catch (error) {
      console.error('任务删除失败:', error);
      throw error;
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};